const fs = require('fs');
const path = require('path');
const _ = require('lodash');

const sendfile = require('koa-sendfile');

const fileUtils = require('./../util/FileUtil');

module.exports = function (router) {

    /**
     *  初始页面 用于测试
     */
    router.get('/', async (ctx) => {
        await ctx.render('index')
    });

    /**
     * 根据路径获取文件列表
     * param: path 需要读取文件的路径
     * return： {
     *             filePath： 文件路径，
     *             fileName： 文件名，
     *             fileType： 文件类型
     *             fileSize:  文件大小， 文件夹时不返回
     *          }
     */
    router.get('/listFile', async (ctx) => {
        let logger = ctx.logger;
        let queryPath = ctx.query.path;
        let result = [];
        if (queryPath) {
            let basicPath = fileUtils.getRealUrl(queryPath);

            let basic = fs.lstatSync(basicPath);
            if (basic.isDirectory()) {
                //读取文件路径内所有东西
                let files = fs.readdirSync(basicPath);
                files.forEach((file) => {
                    if (file.startsWith('$')) {
                        // 跳过 windows 平台下的回收站的文件夹
                        return;
                    }
                    let filePath = path.join(basicPath, file);
                    try {
                        //分析文件， windows 平台下文件夹有权限问题， 进行try/catch
                        let stat = fs.lstatSync(filePath);
                        let data = {
                            "path": path.join(queryPath, file),
                            "name": file
                        };
                        if (stat.isDirectory()) {
                            data.type = 'folder'
                        } else {
                            data.type = fileUtils.getSuffixName(file);
                            data.size = stat.size;
                        }
                        result.push(data);
                    } catch (e) {
                        logger.error(e)
                    }
                });
                ctx.body = result;
            }
        } else {

            let basicDir = [];

            _(ctx.config.basicDir).forEach((dir) => {
                let tmp = {
                    name: dir.name,
                    path: dir.name,
                    type: 'folder'
                };
                basicDir.push(tmp)
            });
            result = _.union(result, basicDir);
        }
        ctx.body = result;
    });
    /**
     * 创建文件夹
     * param : path 需要创建的文件夹路径
     */
    router.post('/mkdir', async (ctx) => {
        let basicPath = ctx.request.body.path;
        let dirName = ctx.request.body.dirName;
        basicPath = fileUtils.getRealUrl(basicPath);

        ctx.response.body = fileUtils.mkdirsSync(path.join(basicPath, dirName))
    });

    /**
     * 下载文件
     * param : path 需要下载文件的路径
     */
    router.get('/download', async (ctx) => {
        let basicPath = fileUtils.getRealUrl(ctx.query.path);
        let fileName = fileUtils.getFileNameForPath(basicPath);
        ctx.set('Content-Type: application/octet-stream');
        ctx.set('Content-disposition', 'attachment;filename=' + fileName);
        await sendfile(ctx, basicPath)
    });


    /**
     * 测试上传  --后期会删除
     */
    router.get('/uploadFile', async (ctx) => {
        ctx.response.body = '<html><head></head><body>\
               <form method="POST" action="/uploadFile"  enctype="multipart/form-data">\
                <input type="text" name="path"><br />\
                <input type="file" name="filefield"><br />\
                <input type="submit">\
              </form>\
            </body></html>';
    });

    /**
     * 修改文件名称 和 移动文件或文件夹
     * param : oldPath 原始文件夹名称路径
     *       : newPath 新文件名称路径/需要移动到的目标位置
     */
    router.post('/rename', async (ctx) => {
        let oldPath = ctx.request.body.oldPath;
        let newPath = ctx.request.body.newPath;
        let result = {};
        result.status = 'success';
        let dirs = ctx.config.basicDir;
        for (let i = 0; i < dirs.length; i++) {
            let dir = dirs[i];
            if (oldPath.startsWith(dir.name)) {
                oldPath = dir.path + oldPath.substr(dir.name.length);
                newPath = dir.path + newPath.substr(dir.name.length);
                break;
            }
        }
        fs.renameSync(oldPath, newPath, function (err) {
            if (err) {
                result.status = 'error'
            }
        });

        ctx.response.body = result
    });


    /**
     * 上传文件 未开发完整
     *
     */
    router.post('/uploadFile', async (ctx) => {
        let uploadPath = ctx.request.body.fields.path;
        uploadPath = fileUtils.getRealUrl(uploadPath);
        ctx.response.body = await fileUtils.uploadFile(ctx, {
            path: uploadPath
        });
    });

    /**
     * 删除文件夹/文件
     * param  path 需要删除的文件夹或文件路径
     */
    router.post('/remove', async (ctx) => {
        let path = ctx.request.body.path;
            path = fileUtils.getRealUrl(path);
        let result = {};
        try {
            await fileUtils.remove(path);
            result.status = 'success';
        } catch (e) {
            result.status = 'error';
        }
        ctx.response.body = JSON.stringify(result);
    });
    return router;
};